<html>

<head>
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>

<body>
    <div id="counter-event-example">
        <p>{{ total }}</p>
        <button-counter v-on:increment="incrementTotal"></button-counter>
        <button-counter v-on:increment="incrementTotal"></button-counter>
    </div>

    <div id="message-event-example" class="demo">
        <p v-for="msg in messages">{{ msg }}</p>
        <button-message v-on:message1="handleMessage"></button-message>
    </div>
</body>
<script>
    /*
            每个 Vue 实例都实现了事件接口，即：

        使用 $on(eventName) 监听事件
        使用 $emit(eventName, optionalPayload) 触发事件
            */
    Vue.component('button-counter', {
        template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
        data: function () {
            return {
                counter: 0
            }
        },
        methods: {
            incrementCounter: function () {
                this.counter += 1
                this.$emit('increment') //子组件通过event向父组件发送消息
            }
        },
    })

    new Vue({
        el: '#counter-event-example',
        data: {
            total: 0
        },
        methods: {
            incrementTotal: function () {
                this.total += 1
            }
        }
    })

    //如何使用载荷 (payload) 数据
    Vue.component('button-message', {
        template: `<div>
    <input type="text" v-model="message" />
    <button v-on:click="handleSendMessage">Send</button>
  </div>`,
        data: function () {
            return {
                message: 'test message'
            }
        },
        methods: {
            handleSendMessage: function () {
                this.$emit('message1', {//message1换成sendMessage为什么不行，有命名冲突？
                    message: this.message
                })
            }
        }
    })

    new Vue({
        el: '#message-event-example',
        data: {
            messages: []
        },
        methods: {
            handleMessage: function (payload) {
                this.messages.push(payload.message)
            }
        }
    })
</script>

</html>